<template>
	<el-dialog class="abow-dialog" :visible.sync="visible" top="50px" :width="((clientWidth-200)>800?800:500)+'px'"
		:title="'用户权限'+(name?'['+name+']':'')" :close-on-click-modal="false" :close-on-press-escape="false">
		<div class="overflowy" :style="{height: clientHeight-260+'px'}">
			<el-tree ref="menuListTree" :data="treeData" show-checkbox node-key="id" :props="defaultProps"
				default-expand-all @check="handleCheckChange"></el-tree>
		</div>
		<template slot="footer">
			<el-button @click="visible = false">{{ $t('views.public.cancel') }}</el-button>
			<el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('views.public.confirm') }}</el-button>
		</template>
	</el-dialog>
</template>

<script>
	import {
		debounce
	} from 'lodash'
	import {
		isEmail,
		isMobile
	} from '@/libs/validate'
	import schema from 'async-validator'
	export default {
		props: {
			name: {
				type: String,
				required: false,
				default: ''
			}
		},
		data() {
			return {
				role_id:null,
				clientWidth: 700,
				clientHeight: 300,
				visible: false,
				defaultCheckedKeys: [],
				treeData: [],
				// data: [{
				// 	id: 1,
				// 	label: '一级 1',
				// 	children: [{
				// 		id: 4,
				// 		label: '二级 1-1',
				// 		children: [{
				// 			id: 9,
				// 			label: '三级 1-1-1'
				// 		}, {
				// 			id: 10,
				// 			label: '三级 1-1-2'
				// 		}]
				// 	}]
				// }, {
				// 	id: 2,
				// 	label: '一级 2',
				// 	children: [{
				// 		id: 5,
				// 		label: '二级 2-1'
				// 	}, {
				// 		id: 6,
				// 		label: '二级 2-2'
				// 	}]
				// }, {
				// 	id: 3,
				// 	label: '一级 3',
				// 	children: [{
				// 		id: 7,
				// 		label: '二级 3-1'
				// 	}, {
				// 		id: 8,
				// 		label: '二级 3-2'
				// 	}]
				// }],
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				deptList: [],
				deptListVisible: false,
				fullscreenLoading: false,
				roleList: [],
				roleIdListDefault: [],
				dataForm: {
					userId: '',
					username: '',
					deptId: '0',
					deptName: '',
					password: '',
					comPassword: '',
					roleIds: '',
					gender: 0,
					email: '',
					mobile: '',
					roleIdList: [],
					status: 1,
					superUser: 0,
					currenId: '',
					name: ''
				},
				foundIds: [],
				checked_ids:[]
			}
		},
		created() {
		},
		computed: {
			dataRule() {
				var validatePassword = (rule, value, callback) => {
					if (!this.dataForm.userId && !/\S/.test(value)) {
						return callback(new Error(this.$t('public.rules.required', {
							name: this.$t('views.public.user.password')
						})))
					}
					callback()
				}
				var validateName = (rule, value, callback) => {
					if (!this.dataForm.userId && !/\S/.test(value)) {
						return callback(new Error(this.$t('public.rules.required', {
							name: '用户名不能为空！'
						})))
					}
					callback()
				}
				var validateComfirmPassword = (rule, value, callback) => {
					if (!this.dataForm.userId && !/\S/.test(value)) {
						return callback(new Error(this.$t('public.rules.required', {
							name: this.$t('views.public.user.comfirmPassword')
						})))
					}
					if (this.dataForm.password !== value) {
						return callback(new Error(this.$t('views.public.user.validate.comfirmPassword')))
					}
					callback()
				}
				var validateEmail = (rule, value, callback) => {
					if (!isEmail(value)) {
						return callback(new Error(this.$t('public.rules.format', {
							name: this.$t('views.public.user.email')
						})))
					}
					callback()
				}
				var validateMobileAsync = (rule, value, callback) => {
					if (!isMobile(value)) {
						return callback(new Error(this.$t('public.rules.format', {
							name: this.$t('views.public.user.mobile')
						})))
					} else {
						callback()
					}
				}
				var validateParentName = (rule, value, callback) => {
					if (!this.dataForm.roleId && !/\S/.test(value)) {
						return callback(new Error('部门名称不能为空！'))
					}
					callback()
				}
				return {
					username: [{
							required: true,
							message: '用户帐户不能为空!',
							trigger: 'blur'
						}
					],
					deptName: [{
							required: true,
							message: this.$t('public.rules.required', {
								name: this.$t('views.public.user.deptName')
							}),
							trigger: 'change'
						},
						{
							validator: validateParentName,
							trigger: 'blur'
						}
					],
					password: [{
						validator: validatePassword,
						trigger: 'blur'
					}],
					comPassword: [{
						validator: validateComfirmPassword,
						trigger: 'blur'
					}],
					email: [{
							required: true,
							message: this.$t('public.rules.required', {
								name: this.$t('views.public.user.email')
							}),
							trigger: 'blur'
						},
						{
							validator: validateEmail,
							trigger: 'blur'
						}
					],
					mobile: [{
							required: true,
							message: this.$t('public.rules.required', {
								name: this.$t('views.public.user.mobile')
							}),
							trigger: 'blur'
						},
						// { validator: validateMobile, trigger: 'blur' }
						{
							validator: validateMobileAsync,
							trigger: 'blur'
						}
					],
					name: [{
							required: true,
							message: '用户名称不能为空！',
							trigger: 'blur'
						},
						{
							validator: validateName,
							trigger: 'blur'
						}

					],
					roleIds: [{
						required: true,
						message: '角色不能为空！',
						trigger: 'change'
					}]
				}
			}
		},
		methods: {
			init() {
				this.visible = true
				this.dataForm.userId = null
				this.dataForm.roleIds = null
				this.dataForm.password = null
				this.dataForm.comPassword = null
				this.$nextTick(() => {
					this.$refs.dataForm.resetFields()
					this.roleIdListDefault = []
				})
			},
			findIds(arr, permission) {
				arr.forEach(item => {
					if (permission.includes(item.url)) {
						this.foundIds.push(item.id);
					}
					if (item.children) {
						this.findIds(item.children, permission);
					}
				});
			},
			// handleCheckChange(a,b,c){
			// 	console.log(a);
			// 	console.log(b);
			// 	console.log(c);
			// },
			handleCheckChange(checkedNodes, checkedObj) {
				let checkedKeys = checkedObj.checkedKeys;
				console.log(checkedKeys);
				var r = checkedKeys.filter(function (s) {
					if(typeof s == 'number'){
						return s;
					}
				});
				this.checked_ids = r;
			},
			update(row) {
				this.clientWidth = document.body.clientWidth;
				this.clientHeight = document.body.clientHeight;
				this.visible = true
				this.$nextTick(() => {
					//用户拥有的权限
					let permission = row.permission || [];
					this.treeData = row.treeData || [];
					this.findIds(this.treeData, permission);
					console.log(this.foundIds);
					this.$refs.menuListTree.setCheckedKeys(this.foundIds);
				})
			},
			// update(row) {
			// 	this.visible = true
			// 	this.$nextTick(() => {
			// 		this.dataForm = Object.assign({}, row)
			// 		this.dataForm.comPassword = row.password
			// 		this.$refs.dataForm.clearValidate()
			// 	})
			// },

			// 所属部门树, 选中
			deptListTreeCurrentChangeHandle(data, node) {
				this.dataForm.deptId = data.deptId
				this.dataForm.deptName = data.name
				this.deptListVisible = false
			},
			// 表单提交
			dataFormSubmitHandle: debounce(function() {
				if(!this.$hasPermission('authority:menu:authorize-save')){
					this.$axios.post('/api/authority/autoRule/authorizeSave', {role_id:this.role_id,menu_ids:this.checked_ids}).then(res => {
						this.$message({
							message: this.$t('views.public.success'),
							type: 'success',
							duration: 500,
							onClose: () => {
								this.visible = false
								this.$emit('refreshDataList')
							}
						})
					}).catch(() => {})
				}else{
					this.visible = false;
					this.$emit('refreshDataList');
					this.$message({
						message: '您没有修改权限',
						type: 'warning',
						duration: 2000,
						onClose: () => {
						}
					})
				}
			}, 1000, {
				leading: true,
				trailing: false
			})
		}
	}
</script>

<style lang="scss">
	.overflowy {
		overflow-y: auto;
	}

	.mod-sys__user {
		.dept-list {

			.el-input__inner,
			.el-input__suffix {
				cursor: pointer;
			}
		}

		.role-list {
			.el-select {
				width: 100%;
			}
		}
	}
</style>